<template>
  <!-- 产品栏目管理 -->
  <div>
    <!-- 头部 -->
    <div class="header">
      <!-- 添加按钮 -->
      <el-button type="primary" round @click="addCategory">添加</el-button>
    </div>
    <!-- 表格 -->
    <div class="table_content">
      <el-table :data="categoryData" style="width: 100%">
        <!-- 序号 -->
        <el-table-column type="index" label="序号" align="center">
        </el-table-column>
        <!-- 产品编号 -->
        <el-table-column prop="id" label="产品编号" align="center">
        </el-table-column>
        <!-- 名称 -->
        <el-table-column prop="name" label="名称" align="center">
        </el-table-column>
        <!-- 图标 -->
        <el-table-column label="图标" align="center">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.icon"
              :preview-src-list="[scope.row.icon]"
            >
            </el-image>
          </template>
        </el-table-column>
        <!-- 排序号 -->
        <el-table-column prop="num" label="排序号" align="center">
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              @click="editCategory(scope.row)"
              type="success"
              size="small"
              round
              plain
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              round
              plain
              style="color: red"
              @click="deleteCategory(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="paginetion">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>
    <!-- 模态框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      @click="dialogClose"
    >
      <!-- 表单区域 -->
      <el-form :model="categoryForm" :rules="rules" ref="category_Form">
        <!-- 栏目名称 -->
        <el-form-item label="栏目名称" prop="name">
          <el-input v-model="categoryForm.name"></el-input>
        </el-form-item>
        <!-- 序号 -->
        <el-form-item label="序号" prop="num">
          <el-input v-model="categoryForm.num"></el-input>
        </el-form-item>
        <!-- 封面 -->
        <el-form-item label="图标" prop="icon">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="categoryForm.icon" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <!-- 提交表单后调用重置表单方法 -->
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { post, get } from "@/utils/request";
import { mapState, mapActions } from "vuex";
import { showFileURL, uploadFileURL } from "@/utils/config";

export default {
  data() {
    return {
      dialogTitle: "",
      uploadFileURL,
      currentPage: 1,
      pageSize: 8,
      categoryForm: {
        name: "",
        icon: "",
        num: "",
      },
      imageUrl: "",
      dialogVisible: false,
      rules: {
        //产品栏目
        name: [{ required: true, message: "请输入栏目名称", trigger: "blur" }],
        //图标
        icon: [{ required: true, message: "请选择图片", trigger: "change" }],
      },
    };
  },
  computed: {
    ...mapState("category", ["categoryData"]),
    ...mapState("category", ["total"]),
  },
  methods: {
    ...mapActions("category", ["getAllCategoryData"]),
    //获取栏目信息
    queryCategoryData() {
      let data = {
        page: this.currentPage,
        pageSize: this.pageSize,
      };
      this.getAllCategoryData(data);
    },
    //控制每页数据条数
    handleSizeChange(val) {
      this.pageSize = val;
      // console.log(`每页 ${val} 条`);
      //将当前的页数重置到第一页
      this.currentPage = 1;
      this.queryCategoryData();
    },
    //控制当前页码在那一页
    handleCurrentChange(val) {
      this.currentPage = val;
      // console.log(`当前页: ${val}`);
      //重新调用获取产品数据的方式
      this.queryCategoryData();
    },
    //添加按钮
    addCategory() {
      this.dialogVisible = true;
      this.dialogTitle = "添加栏目";
      this.categoryForm = {};
      //将imgurl置空
      this.imageUrl = "";
    },
    //编辑解决
    editCategory(row) {
      this.categoryForm = { ...row };
      //预览图片地址赋值
      this.imageUrl = this.categoryForm.icon;
      this.dialogTitle = "编辑栏目";
      this.dialogVisible = true;
    },
    //删除解决
    async deleteCategory(deleteId) {
      // console.log(deleteId);
      let res = await get("/productCategory/deleteById", { id: deleteId });
      if (res.status == 200) {
        this.$message({
          message: res.message,
          type: "success",
        });
        //刷新页面
        this.queryCategoryData();
      } else {
        this.$message.error(res.message);
      }
    },
    //提交栏目
    submitForm() {
      this.$refs["category_Form"].validate(async (valid) => {
        if (valid) {
          let res = await post(
            "/productCategory/saveOrUpdate",
            this.categoryForm
          );
          if (res.status == 200) {
            this.$message({
              message: res.message,
              type: "success",
            });
            //刷新页面
            this.dialogClose();
            this.queryCategoryData();
          } else {
            this.$message.error(res.message);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //图片提交路径
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(res);
      //上传成功后更新categoryForm.photo的路径
      this.categoryForm.icon = showFileURL + res.data.id;
    },
    //图片提交前限制
    beforeAvatarUpload(file) {
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isLt3M) {
        this.$message.error("上传头像图片大小不能超过 3MB!");
      }
    },
    //模态框关闭
    dialogClose() {
      this.$refs["category_Form"].resetFields();
      setTimeout(() => {
        this.dialogVisible = false;
        this.categoryForm = {};
      }, 200);
    },
  },
  created() {
    this.queryCategoryData();
  },
  mounted() {},
};
</script>
<style scoped>
.paginetion {
  margin-top: 10px;
  text-align: right;
}
</style>